<template>
  <div class="order-tracking-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>订单跟踪</h3>
          <el-input
            v-model="quickSearch"
            placeholder="快速搜索订单号、物流单号"
            style="width: 300px;"
            clearable
            @keyup.enter="handleQuickSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="订单号">
            <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
          </el-form-item>
          <el-form-item label="物流单号">
            <el-input v-model="searchForm.trackingNo" placeholder="请输入物流单号" clearable />
          </el-form-item>
          <el-form-item label="客户">
            <el-input v-model="searchForm.customer" placeholder="请输入客户名称" clearable />
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待确认" value="pending" />
              <el-option label="已确认" value="confirmed" />
              <el-option label="备货中" value="preparing" />
              <el-option label="已发货" value="shipped" />
              <el-option label="运输中" value="in_transit" />
              <el-option label="派送中" value="delivering" />
              <el-option label="已签收" value="delivered" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 订单列表 -->
      <div class="order-list">
        <el-card 
          v-for="order in orders" 
          :key="order.id" 
          class="order-card"
          shadow="hover"
        >
          <div class="order-header-section">
            <div class="order-info">
              <div class="order-no">
                订单号：<span class="highlight">{{ order.orderNo }}</span>
              </div>
              <div class="order-time">
                下单时间：{{ order.createTime }}
              </div>
            </div>
            <div class="order-status">
              <el-tag :type="getStatusType(order.status)" size="large">
                {{ getStatusText(order.status) }}
              </el-tag>
            </div>
          </div>

          <el-divider />

          <div class="order-content">
            <div class="customer-info">
              <div class="info-row">
                <el-icon><User /></el-icon>
                <span>客户：{{ order.customerName }}</span>
              </div>
              <div class="info-row">
                <el-icon><Phone /></el-icon>
                <span>电话：{{ order.contactPhone }}</span>
              </div>
              <div class="info-row">
                <el-icon><Location /></el-icon>
                <span>地址：{{ order.deliveryAddress }}</span>
              </div>
            </div>

            <div class="products-info">
              <div class="product-item" v-for="(product, index) in order.products" :key="index">
                <div class="product-name">{{ product.productName }}</div>
                <div class="product-spec">{{ product.specification }}</div>
                <div class="product-quantity">x{{ product.quantity }}</div>
              </div>
            </div>

            <div class="amount-info">
              <div class="amount-label">订单金额</div>
              <div class="amount-value">¥{{ order.totalAmount.toFixed(2) }}</div>
            </div>
          </div>

          <el-divider />

          <!-- 物流信息 -->
          <div v-if="order.logistics" class="logistics-info">
            <div class="logistics-header">
              <div class="logistics-company">
                <el-icon><Van /></el-icon>
                <span>{{ order.logistics.company }}</span>
              </div>
              <div class="logistics-no">
                物流单号：{{ order.logistics.trackingNo }}
                <el-button 
                  type="primary" 
                  size="small" 
                  text
                  @click="copyTrackingNo(order.logistics.trackingNo)"
                >
                  <el-icon><CopyDocument /></el-icon>
                  复制
                </el-button>
              </div>
            </div>

            <!-- 物流进度 -->
            <div class="logistics-progress">
              <el-steps :active="getLogisticsStep(order.status)" align-center>
                <el-step title="订单确认" :description="order.confirmedTime" />
                <el-step title="仓库备货" :description="order.preparingTime" />
                <el-step title="已发货" :description="order.shippedTime" />
                <el-step title="运输中" :description="order.transitTime" />
                <el-step title="派送中" :description="order.deliveringTime" />
                <el-step title="已签收" :description="order.deliveredTime" />
              </el-steps>
            </div>

            <!-- 物流轨迹 -->
            <div class="logistics-track">
              <el-button 
                type="primary" 
                text
                @click="handleViewTrack(order)"
              >
                查看物流轨迹
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
          </div>

          <div v-else class="no-logistics">
            <el-empty description="暂无物流信息" :image-size="80" />
          </div>

          <el-divider />

          <!-- 操作按钮 -->
          <div class="order-actions">
            <el-button 
              type="primary" 
              size="small"
              @click="handleViewDetail(order)"
            >
              <el-icon><View /></el-icon>
              查看详情
            </el-button>
            <el-button 
              v-if="order.status === 'pending'" 
              type="success" 
              size="small"
              @click="handleConfirmOrder(order)"
            >
              <el-icon><Check /></el-icon>
              确认订单
            </el-button>
            <el-button 
              v-if="order.status === 'confirmed' || order.status === 'preparing'" 
              type="warning" 
              size="small"
              @click="handleShipOrder(order)"
            >
              <el-icon><Van /></el-icon>
              发货
            </el-button>
            <el-button 
              v-if="order.status === 'shipped' || order.status === 'in_transit' || order.status === 'delivering'" 
              type="info" 
              size="small"
              @click="handleUpdateLogistics(order)"
            >
              <el-icon><Refresh /></el-icon>
              更新物流
            </el-button>
            <el-button 
              size="small"
              @click="handleContactCustomer(order)"
            >
              <el-icon><ChatDotRound /></el-icon>
              联系客户
            </el-button>
            <el-button 
              v-if="['pending', 'confirmed'].includes(order.status)" 
              type="danger" 
              size="small"
              @click="handleCancelOrder(order)"
            >
              <el-icon><Close /></el-icon>
              取消订单
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 物流轨迹对话框 -->
    <el-dialog
      v-model="trackDialogVisible"
      title="物流轨迹"
      width="700px"
    >
      <div v-if="currentOrder && currentOrder.logistics">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="物流单号">{{ currentOrder.logistics.trackingNo }}</el-descriptions-item>
          <el-descriptions-item label="物流公司">{{ currentOrder.logistics.company }}</el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider>物流轨迹</el-divider>

        <el-timeline>
          <el-timeline-item
            v-for="(track, index) in currentOrder.logistics.tracks"
            :key="index"
            :timestamp="track.time"
            :color="index === 0 ? '#409EFF' : '#909399'"
            placement="top"
          >
            <el-card :class="index === 0 ? 'current-track' : ''">
              <div class="track-info">
                <div class="track-desc">{{ track.description }}</div>
                <div class="track-location">{{ track.location }}</div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="600px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="订单号">
          <el-input v-model="currentOrder.orderNo" disabled />
        </el-form-item>
        <el-form-item label="物流公司" prop="company">
          <el-select v-model="shipForm.company" placeholder="请选择物流公司" style="width: 100%">
            <el-option label="顺丰速运" value="顺丰速运" />
            <el-option label="圆通速递" value="圆通速递" />
            <el-option label="中通快递" value="中通快递" />
            <el-option label="韵达快递" value="韵达快递" />
            <el-option label="申通快递" value="申通快递" />
            <el-option label="京东物流" value="京东物流" />
            <el-option label="德邦物流" value="德邦物流" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="发货备注" prop="remark">
          <el-input 
            v-model="shipForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入发货备注（选填）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitShip" :loading="submitLoading">
          确定发货
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  User, 
  Phone, 
  Location, 
  Van, 
  CopyDocument,
  ArrowRight,
  View,
  Check,
  Close,
  ChatDotRound
} from '@element-plus/icons-vue'
import { useClipboard } from '@vueuse/core'

const { copy } = useClipboard()

// 响应式数据
const quickSearch = ref('')
const trackDialogVisible = ref(false)
const shipDialogVisible = ref(false)
const submitLoading = ref(false)
const shipFormRef = ref()
const currentOrder = ref({})

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  trackingNo: '',
  customer: '',
  status: ''
})

// 发货表单
const shipForm = reactive({
  company: '',
  trackingNo: '',
  remark: ''
})

// 表单验证规则
const shipRules = {
  company: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNo: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
})

// 订单数据
const orders = ref([
  {
    id: 1,
    orderNo: 'SO20240115001',
    customerName: '张三',
    contactPhone: '13800138000',
    deliveryAddress: '北京市朝阳区XXX街道XXX小区XXX号楼XXX单元',
    totalAmount: 15000,
    status: 'in_transit',
    createTime: '2024-01-15 10:00:00',
    confirmedTime: '2024-01-15 10:30:00',
    preparingTime: '2024-01-15 14:00:00',
    shippedTime: '2024-01-16 09:00:00',
    transitTime: '2024-01-16 15:00:00',
    deliveringTime: '',
    deliveredTime: '',
    products: [
      { productName: 'iPhone 15', specification: '128GB 黑色', quantity: 3 }
    ],
    logistics: {
      company: '顺丰速运',
      trackingNo: 'SF1234567890',
      tracks: [
        {
          time: '2024-01-16 15:30:00',
          description: '快件已到达【北京转运中心】',
          location: '北京市'
        },
        {
          time: '2024-01-16 12:00:00',
          description: '快件离开【上海转运中心】，已发往【北京转运中心】',
          location: '上海市'
        },
        {
          time: '2024-01-16 09:00:00',
          description: '快件已揽收',
          location: '上海市浦东新区'
        }
      ]
    }
  },
  {
    id: 2,
    orderNo: 'SO20240115002',
    customerName: '北京科技有限公司',
    contactPhone: '010-88888888',
    deliveryAddress: '北京市海淀区中关村XXX大厦XXX层',
    totalAmount: 8500,
    status: 'preparing',
    createTime: '2024-01-15 14:00:00',
    confirmedTime: '2024-01-15 14:30:00',
    preparingTime: '2024-01-15 15:00:00',
    shippedTime: '',
    transitTime: '',
    deliveringTime: '',
    deliveredTime: '',
    products: [
      { productName: 'MacBook Pro', specification: '13英寸 M2芯片', quantity: 1 }
    ],
    logistics: null
  },
  {
    id: 3,
    orderNo: 'SO20240115003',
    customerName: '王总',
    contactPhone: '13900139000',
    deliveryAddress: '上海市浦东新区XXX路XXX号',
    totalAmount: 25000,
    status: 'delivered',
    createTime: '2024-01-10 16:00:00',
    confirmedTime: '2024-01-10 16:30:00',
    preparingTime: '2024-01-11 09:00:00',
    shippedTime: '2024-01-11 14:00:00',
    transitTime: '2024-01-12 10:00:00',
    deliveringTime: '2024-01-13 08:00:00',
    deliveredTime: '2024-01-13 15:30:00',
    products: [
      { productName: 'iPhone 15', specification: '256GB 白色', quantity: 5 }
    ],
    logistics: {
      company: '京东物流',
      trackingNo: 'JD9876543210',
      tracks: [
        {
          time: '2024-01-13 15:30:00',
          description: '您的快件已签收，感谢使用京东物流',
          location: '上海市浦东新区'
        },
        {
          time: '2024-01-13 08:00:00',
          description: '快件正在派送中，派送员：李师傅，电话：138****1234',
          location: '上海市浦东新区'
        },
        {
          time: '2024-01-12 10:00:00',
          description: '快件已到达【上海浦东新区配送站】',
          location: '上海市浦东新区'
        },
        {
          time: '2024-01-11 14:00:00',
          description: '快件已揽收',
          location: '北京市'
        }
      ]
    }
  }
])

// 方法
const getStatusText = (status) => {
  const map = {
    pending: '待确认',
    confirmed: '已确认',
    preparing: '备货中',
    shipped: '已发货',
    in_transit: '运输中',
    delivering: '派送中',
    delivered: '已签收',
    cancelled: '已取消'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    confirmed: 'primary',
    preparing: 'info',
    shipped: 'success',
    in_transit: 'success',
    delivering: 'success',
    delivered: 'success',
    cancelled: 'danger'
  }
  return map[status] || 'info'
}

const getLogisticsStep = (status) => {
  const map = {
    pending: 0,
    confirmed: 1,
    preparing: 2,
    shipped: 3,
    in_transit: 4,
    delivering: 5,
    delivered: 6
  }
  return map[status] || 0
}

const copyTrackingNo = (trackingNo) => {
  copy(trackingNo)
  ElMessage.success('物流单号已复制')
}

const handleQuickSearch = () => {
  searchForm.orderNo = quickSearch.value
  handleSearch()
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  quickSearch.value = ''
  Object.assign(searchForm, {
    orderNo: '',
    trackingNo: '',
    customer: '',
    status: ''
  })
  handleSearch()
}

const handleViewTrack = (order) => {
  currentOrder.value = order
  trackDialogVisible.value = true
}

const handleViewDetail = (order) => {
  ElMessage.info('跳转到订单详情页面')
}

const handleConfirmOrder = async (order) => {
  try {
    await ElMessageBox.confirm('确定要确认该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = orders.value.findIndex(item => item.id === order.id)
    if (index > -1) {
      orders.value[index].status = 'confirmed'
      orders.value[index].confirmedTime = new Date().toLocaleString()
      ElMessage.success('订单确认成功')
    }
  } catch {
    // 用户取消操作
  }
}

const handleShipOrder = (order) => {
  currentOrder.value = order
  resetShipForm()
  shipDialogVisible.value = true
}

const handleSubmitShip = async () => {
  if (!shipFormRef.value) return

  try {
    await shipFormRef.value.validate()

    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    const index = orders.value.findIndex(item => item.id === currentOrder.value.id)
    if (index > -1) {
      orders.value[index].status = 'shipped'
      orders.value[index].shippedTime = new Date().toLocaleString()
      orders.value[index].logistics = {
        company: shipForm.company,
        trackingNo: shipForm.trackingNo,
        tracks: [
          {
            time: new Date().toLocaleString(),
            description: '快件已揽收',
            location: '发货地'
          }
        ]
      }
      ElMessage.success('发货成功')
    }

    shipDialogVisible.value = false
  } catch (error) {
    console.error('发货失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleUpdateLogistics = async (order) => {
  ElMessage.info('正在更新物流信息...')
  // 模拟更新物流信息
  setTimeout(() => {
    ElMessage.success('物流信息已更新')
  }, 1000)
}

const handleContactCustomer = (order) => {
  ElMessage.info(`正在拨打客户电话：${order.contactPhone}`)
}

const handleCancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = orders.value.findIndex(item => item.id === order.id)
    if (index > -1) {
      orders.value[index].status = 'cancelled'
      ElMessage.success('订单已取消')
    }
  } catch {
    // 用户取消操作
  }
}

const resetShipForm = () => {
  Object.assign(shipForm, {
    company: '',
    trackingNo: '',
    remark: ''
  })
  shipFormRef.value?.clearValidate()
}

const loadData = () => {
  pagination.total = orders.value.length
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.order-tracking-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.order-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.order-header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  flex: 1;
}

.order-no {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.order-no .highlight {
  color: #409EFF;
}

.order-time {
  font-size: 14px;
  color: #909399;
}

.order-content {
  display: grid;
  grid-template-columns: 2fr 2fr 1fr;
  gap: 20px;
  margin: 16px 0;
}

.customer-info,
.products-info,
.amount-info {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-name {
  flex: 1;
  font-weight: bold;
  color: #303133;
}

.product-spec {
  color: #909399;
  margin: 0 8px;
}

.product-quantity {
  color: #606266;
}

.amount-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.amount-label {
  font-size: 14px;
  color: #909399;
}

.amount-value {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}

.logistics-info {
  padding: 16px;
  background: #f0f9ff;
  border-radius: 4px;
}

.logistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.logistics-company {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.logistics-no {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.logistics-progress {
  margin: 30px 0;
}

.logistics-track {
  text-align: center;
  margin-top: 20px;
}

.no-logistics {
  padding: 40px;
  text-align: center;
}

.order-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.current-track {
  background: #f0f9ff;
  border-color: #409EFF;
}

.track-info {
  padding: 8px;
}

.track-desc {
  font-size: 15px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.track-location {
  font-size: 13px;
  color: #909399;
}
</style>

